package it.sebsibenal.server.dao.impl;

import it.sebsibenal.shared.HasId;

import java.util.List;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public abstract class AbstractDatastoreDAO<T extends HasId> {

	private Class<T> beanClass;
	
	public AbstractDatastoreDAO(Class<T> beanClass) {
		super();
		this.beanClass = beanClass;
		ObjectifyService.register(beanClass);
	}

	public List<T> findAll() {
		return this.findAllWithOrderBy();
	}
	
	protected Objectify getService() {
		return ObjectifyService.begin();
	}

	public List<T> findAllWithOrderBy(String... orderBy) {
		Objectify ofy = ObjectifyService.begin();
		Query<T> query = ofy.query(beanClass);
		for (int i = 0; i < orderBy.length; i++) {
			query = query.order(orderBy[i]);	
		}
		return query.list();
	}
	
	public T findById(Long id) {
		Objectify ofy = ObjectifyService.begin();
		return ofy.find(beanClass, id);
	}
	
	public void insert(T bean) {
		Objectify ofy = ObjectifyService.begin();
		Key<T> key = ofy.put(bean);
		bean.setId(key.getId());
	}


	public void update(T bean) {
		Objectify ofy = ObjectifyService.begin();
		ofy.put(bean);
	}

	public void delete(T bean) {
		Objectify ofy = ObjectifyService.begin();
		ofy.delete(bean);
	}


}
